package com.bjsxt.base.conn017_concurrent工具类;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

public class TestThread {

    public static void main(String[] args) throws InterruptedException {
        for(int i=0; i<10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    TestThread tt = new TestThread();
                    try {
                        tt.m3(Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "线程 " + i).start();
        }
    }

    public void m3(String name) throws InterruptedException {
        System.out.println(name + " start...");
        final MyService ms = new MyService();
        final Map<String, Integer> map = new HashMap();
        final CountDownLatch latch = new CountDownLatch(2);
        new Thread(){
            @Override
            public void run() {
                int sum = ms.m1();
                map.put("m1", sum);
                latch.countDown();
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                int sum = ms.m2();
                map.put("m2", sum);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        }.start();
        latch.await();
        System.out.println("两个线程都执行完毕...");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "   ,   " + entry.getValue());
        }
    }

}

class MyService{

    public int m1() {
        System.out.println("m1");
        int sum = 0;
        for(int i=1; i<1000000; i++) {
            sum += i;
        }
        return sum;
    }

    public int m2() {
        System.out.println("m2");
        int sum = 0;
        for(int i=1; i<1000000; i++) {
            sum += i;
        }
        return sum;
    }

}


